<?php

namespace app\core\util;

use app\core\Util;
use Exception;
use GuzzleHttp\Client;
use think\facade\Log;

/**
 * @extends Util<http>
 */
class http extends Util
{
    private $client;

    public function __construct()
    {
        $this->client = new Client([
            'timeout'  => 5.0, // 5秒 超时
        ]);
    }

    private function __clone()
    {}

    public function request($method, $url, $options = [])
    {
        try {
            $client = $this->client;
            $response = $client->request($method, $url, $options);
            $status = $response->getStatusCode();
            if($status != 200){
                throw new Exception('Http Status Code:' . $status);
            }
            return $response->getBody()->getContents();
        } catch (Exception $e) {
            Log::error("Http Error: " . $e->getMessage());
            Log::error("Http Url: " . $url);
            Log::error("Http Options: ");
            Log::error($options);
            // 处理请求异常
            return null;
        }
    }
}